package com.irixel.hdc.controllers;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.irixel.hdc.dto.TipoFacturaDTO;

@Controller
public class TipoFacturaController {

	@Autowired
	private JdbcTemplate jdbcTemplate;

	@RequestMapping(value = "/tiposfactura", method = RequestMethod.GET)
	public @ResponseBody
	List<TipoFacturaDTO> getTipos() {
		List<TipoFacturaDTO> tipos = jdbcTemplate.query(
				"select * from tipofactura order by numCuenta asc",
				new RowMapper<TipoFacturaDTO>() {
					@Override
					public TipoFacturaDTO mapRow(ResultSet rs, int num)
							throws SQLException {
						TipoFacturaDTO ret = new TipoFacturaDTO();
						ret.setId(rs.getLong("id"));
						ret.setNombre(rs.getString("nombre"));
						ret.setIdPadre(rs.getLong("padre"));
						ret.setNumCuenta(rs.getLong("numCuenta"));

						return ret;
					}
				});

		// Let's group them
		Map<Long, TipoFacturaDTO> tree = new HashMap<Long, TipoFacturaDTO>();
		for (TipoFacturaDTO dto : tipos) {
			if (dto.getIdPadre().longValue() == 0) {
				tree.put(dto.getId(), dto);
			} else {
				tree.get(dto.getIdPadre()).getHijos().add(dto);
			}
		}

		return new ArrayList<TipoFacturaDTO>(tree.values());
	}

}
